<template>
  <div>
    <el-button
      style="justify-content: flex-start; width: 220px; overflow: hidden"
      @click="openModal"
    >
      {{ showStr }}
    </el-button>

    <Modal
      v-bind="$attrs"
      ref="modalRef"
      :title="'员工选择'"
      :loading="modalLoading"
      :options="options"
      :position="{ top: '10vh' }"
      @register="registerModal"
      @confirm="handleConfirm"
      @cancel="handleCancel"
    >
      <template #title_right>
        <div style="display: flex; align-items: center; margin-right: 10px">
          <span> 工种:</span>
          <el-select-v2
            style="width: 200px; padding-left: 10px"
            v-model="jobTitleId"
            :options="gongZhongOptions"
            filterable
            placeholder="请选择工种"
            @change="handleGongZhongChange"
          />
        </div>
      </template>
    </Modal>
  </div>
</template>

<script setup lang="ts">
  import { useVxeModal } from '@/components/ui/vxe-modal'
  import { getSycConstant, getListItem } from '@/utils'
  import Modal from '@/components/ui/vxe-form/src/components/select-modal/Modal.vue'
  import { FormV0 } from '../data'
  import { getRenYuanList } from '@/api/personAdmin'

  const props = withDefaults(
    defineProps<{
      modelValue: string[]
      gongZhongID: string
      formData: FormV0
      gongZhongOptions: LabelValueOption[]
      gongXuOptions: LabelValueOption[]
    }>(),
    { modelValue: () => [] }
  )

  const emits = defineEmits(['update:modelValue', 'update:gongZhongID', 'change', 'confirm'])

  const modalRef = ref<InstanceType<typeof Modal>>()

  const [registerModal, modalMethods] = useVxeModal()

  const selectList = computed({
    get: () => props.modelValue,
    set: (newValue) => {
      emits('change', newValue)
      emits('update:modelValue', newValue)
    }
  })

  watch(
    () => props.modelValue,
    (newValue) => {
      modalCurrentSelectList.value = newValue
    }
  )

  // 避免选择工种后列表与选择str不同步
  const modalCurrentSelectList = ref<string[]>([])

  const modalLoading = ref(false)
  const options = ref<LabelValueOption[]>([])
  const optionsCopy = ref<LabelValueOption[]>([])
  const jobTitleId = ref('')

  const selectListItems = computed(() => {
    return modalCurrentSelectList.value.map((v) => getListItem(options.value, v))
  })

  const showStr = computed(() => selectListItems.value.map((v) => v?.label).join(','))

  const init = async () => {
    await getGongZhong()
    await handleGongZhongChange()

    // 默认全选
    selectList.value = options.value.map((v) => v.value)
    emits('update:gongZhongID', jobTitleId.value)
  }

  // 获取默认工种
  const getGongZhong = () => {
    const { gongXuId } = props.formData
    const gongXuName = getListItem(props.gongXuOptions, gongXuId)?.label

    if (gongXuName === '细纱' || gongXuName === '络筒') {
      jobTitleId.value = getListItem(props.gongZhongOptions, '挡落一体', 'label')?.value
    } else {
      jobTitleId.value = getListItem(props.gongZhongOptions, '前纺挡车', 'label')?.value
    }
  }

  const handleGongZhongChange = async () => {
    const { tsIdSelect, gongXuId, quYuValue } = props.formData
    const { startTsId, endTsId } = tsIdSelect
    let data = {
      tsIdStart: startTsId,
      tsIdEnd: endTsId,
      jobTitleId: jobTitleId.value,
      name: '',
      // TODO: 不知道 111 是什么东西
      craftNodeId: gongXuId === '111' ? '' : gongXuId
    }

    modalLoading.value = true
    await getRenYuanList(data, getSycConstant('quYuNum'), quYuValue)
      .then((res) => {
        // 清空选项
        modalCurrentSelectList.value = []
        modalRef.value?.handleCheckAll(false)
        options.value = res.map((v) => {
          return {
            ...v,
            label: v.firstName,
            value: v.personDocumentId
          }
        })
        // 全选
        modalCurrentSelectList.value = options.value.map((v) => v.value)
        nextTick(() => {
          modalRef.value?.handleCheckAll(true)
        })
      })
      .catch((err) => {
        console.error(err)
      })
      .finally(() => {
        modalLoading.value = false
      })
  }

  const openModal = () => {
    modalCurrentSelectList.value = selectList.value
    optionsCopy.value = options.value

    modalMethods.openModal(true, {
      defaultChecked: modalCurrentSelectList.value
    })
  }

  const handleConfirm = (val) => {
    selectList.value = val

    emits('update:gongZhongID', jobTitleId.value)

    emits('confirm')
  }

  const handleCancel = (e) => {
    // 还原数据
    modalCurrentSelectList.value = selectList.value
    jobTitleId.value = props.gongZhongID
    options.value = optionsCopy.value
  }

  defineExpose({ init })
</script>

<style lang="scss" scoped></style>
